package ca.seia.comp6521.a2.util;

public class ArrayUtil {
	
	public static int binarySearch(String[] a, int key) {
        return binarySearch0(a, 0, a.length, key);
    }

//	public static int binarySearch(String[] a, int fromIndex, int toIndex, String key) {
//		rangeCheck(a.length, fromIndex, toIndex);
//		return binarySearch0(a, fromIndex, toIndex, key);
//	}

	// Like public version, but without range checks.
	private static int binarySearch0(String[] a, int fromIndex, int toIndex, int key) {
		int low = fromIndex;
		int high = toIndex - 1;

		while (low <= high) {
			int mid = (low + high) >>> 1;
			//int midVal = Integer.parseInt(a[mid]);
			int midVal = NumberUtil.parseInt(a[mid]);
			int cmp = 0;
			if (midVal > key) {
				cmp = 1;
			} else if (midVal < key) {
				cmp = -1;
			}

			if (cmp < 0)
				low = mid + 1;
			else if (cmp > 0)
				high = mid - 1;
			else
				return mid; // key found
		}
		return -(low + 1); // key not found.
	}
	
	private static void rangeCheck(int length, int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IllegalArgumentException(
                "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
        }
        if (fromIndex < 0) {
            throw new ArrayIndexOutOfBoundsException(fromIndex);
        }
        if (toIndex > length) {
            throw new ArrayIndexOutOfBoundsException(toIndex);
        }
    }
	
}
